<template>
	<view v-if="mode == 'create'" @click="chooseFile">
		<slot></slot>
	</view>
</template>

<script>
	export default {
		props: {
			attachmentList: {
				type: Array //附件列表
			},
			mode: {
				type: String //模式： create => 可新增或编辑附件 不填或其他 => 只能查看附件
			},
			uploadFileUrl: {
				type: String,
				dafault: '#' // 上传文件的服务器url
			},
			showProcess: {
				type: Boolean,
				default: true //是否显示进度，默认显示
			},
			header: {
				type: Object //上传图片到服务器时，HTTP 请求 Header
			},
			limit: {
				type: Number, //限制可上传的图片数量
				default: null
			},
			fileKeyName: {
				type: String,
				default: 'file' //用于在服务端通过自定义key值获取该文件数据
			},
			canUploadFile: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			list() {
				return this.attachmentList;
			}
		},
		data() {
			return {};
		},
		methods: {
			previewImg(url) {
				uni.previewImage({
					current: 0,
					urls: [url]
				});
			},
			async chooseFile() {
				console.log("开始上传")
				if (this.limit != null && !isNaN(this.limit)) {
					if (this.list.length >= this.limit) {
						uni.showToast({
							title: '已达到最大上传数量',
							icon: 'none'
						});
						return;
					}
				}

				var canUploadFile = this.canUploadFile;
				// 非APP平台不可以上传文件
				// #ifndef APP-PLUS || MP-WEIXIN
				canUploadFile = false;
				// #endif

				// #ifdef APP-PLUS
				if (canUploadFile) {
					const open = uni.requireNativePlugin('chuck-filemanager');
					var temp = await new Promise(resoleve => {
						open.onIntent('996', path => {
							resoleve(path);
						});
					})
					var tempFiles = ['file:///' + temp];
				}
				// #endif

				if (!canUploadFile) {
					var temps = await uni.chooseImage({
						count: this.limit == null || this.limit - this.list.length > 9 ? 9 : 9 - limit,
						sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album'] //从相册选择
					});

					if (typeof temps[1] == 'undefined') {
						return;
					}
					var tempFiles = temps[1].tempFilePaths;
				} else {
					// #ifdef MP-WEIXIN
					var res = await uni.showActionSheet({
						itemList: ['选择图片', '选择文件']
					})
					if (res[1].tapIndex == 0) {
						this.$emit('choose')
						console.log("选择图片")
					} else {
						//微信从客户端选择文件
						var temps = await new Promise((resolve, reject) => {
							wx.chooseMessageFile({
								count: 1,
								type: 'file',
								success(res) {
									// tempFilePath可以作为img标签的src属性显示图片
									const tempFilePaths = res.tempFiles;
									resolve(tempFilePaths);
								}
							})
						})

						var tempFiles = temps.map((ele, index) => {
							return ele.path;
						})

						var fileNames = temps.map((ele, index) => {
							return ele.name;
						})
					}
					// #endif
				}


				for (let i in tempFiles) {
					let path = tempFiles[i];
					if (typeof fileNames != 'undefined' && typeof fileNames[i] != 'undefined') {
						var fileName = fileNames[i];
					} else {
						var fileName = path.split('/');
						fileName = fileName[fileName.length - 1];
					}
					let index = this.list.length;

					// 开始上传，先暂存文件
					this.list.push({
						fileName: fileName,
						url: path,
						type: this.isImg(path) ? 'image' : 'file',
						index: index,
						uploadTask: uploadTask,
						process: 0
					});
					this.$forceUpdate();
					console.log("开始上传了")
					var uploadTask = await uni.uploadFile({
						url: this.uploadFileUrl,
						filePath: path,
						name: "file",
						headers: {
							"Content-Type": "multipart/form-data" //必须支持文件流存储
						},
						formData: {
							"type": 1,
						},
						success: res => {
							// 上传完成后处理
							this.$emit('uploadSuccess', res);
							if (res.statusCode == 200) {
								this.$set(this.list[index], 'process', 100);
								this.$emit('update:attachmentList', this.list);
								this.$forceUpdate();
							} else {

							}
						}
					});
					console.log("开始上传了")
					uploadTask.onProgressUpdate(res => {
						//此接口不显示真实进度， 所以需要特殊处理
						if (res.progress < 90) {
							this.$set(this.list[index], 'process', res.progress);
							this.$forceUpdate();
						}
					});
				}
			},
			//根据文件名，返回时是否是图片类型
			isImg(filePath) {
				let index = filePath.lastIndexOf('.');
				let ext = filePath.substr(index + 1);
				var temp = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
				return temp;
			}
		}
	};
</script>

<style lang="less" scoped>
</style>
